package io.renren.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import io.renren.common.validator.Assert;
import io.renren.dao.SysDeptDao;
import io.renren.dao.SysRoleDao;
import io.renren.dao.SysUserDao;
import io.renren.dao.SysUserRoleDao;
import io.renren.dao.TokenDao;
import io.renren.entity.SysDeptEntity;
import io.renren.entity.SysRoleEntity;
import io.renren.entity.SysUserEntity;
import io.renren.entity.SysUserRoleEntity;
import io.renren.entity.TokenEntity;
import io.renren.form.SysUserForm;
import io.renren.response.SysRoleResponse;
import io.renren.response.SysUserResponse;
import io.renren.service.SysUserService;
import io.renren.util.HttpClientUtil;
import io.renren.util.ShiroUtils;

@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Value("${rongyun.appkey}")
	String rongyunappkey;
	@Value("${rongyun.appsecret}")
	String rongyunappsecret;
	@Value("${rongyun.url}")
	String rongyunurl;
	

	@Autowired
	SysRoleDao roleDao;
	
	@Autowired
	SysDeptDao deptDao;
	
	@Autowired
	SysUserRoleDao urDao;
	
	@Autowired
	TokenDao tokenDao;
	public static void main(String[] args) {
		Long timestamp=System.currentTimeMillis()/1000;

		int nonce = (int) ((Math.random()*9+1)*10000);
		System.out.println(DigestUtils.sha1Hex(("coJ0yUr0E52h"+nonce+timestamp).getBytes()));
		
		System.out.println( System.currentTimeMillis()/1000);
	}
	/**
	 * 用户登录 
	 */
	@Override
	public SysUserResponse login(SysUserForm user) {
		SysUserEntity u = this.selectOne(new EntityWrapper<SysUserEntity>().eq("username", user.getUsername()).or().eq("mobile", user.getUsername()));
		Assert.isNull(u, "用户不存在");
		String password = ShiroUtils.sha256(user.getPassword(), u.getSalt());
		SysUserEntity userEntity = this.selectOne(new EntityWrapper<SysUserEntity>().eq("username", user.getUsername())
				.or().eq("mobile", user.getUsername()).eq("password", password));
		Assert.isNull(userEntity, "用户名或密码错误");
		SysUserResponse rUser = new SysUserResponse();
		BeanUtils.copyProperties(userEntity, rUser);
		SysDeptEntity dept = deptDao.selectById(rUser.getDeptId());
		rUser.setDeptName(dept.getName());
		List<SysUserRoleEntity> urs = urDao.selectList(new EntityWrapper<SysUserRoleEntity>().eq("user_id", rUser.getUserId()));
		List<SysRoleResponse> urrs = new ArrayList<SysRoleResponse>();
		for (SysUserRoleEntity ur : urs) {
			SysRoleEntity role = roleDao.selectById(ur.getRoleId());
			SysRoleResponse rr = new SysRoleResponse();
			BeanUtils.copyProperties(role, rr);
			urrs.add(rr);
		}
		rUser.setRoles(urrs);
		
		TokenEntity token = tokenDao.selectById(rUser.getUserId());
		if(null!=token){
			rUser.setRyToken(token.getToken());
		}else{
			Long timestamp=System.currentTimeMillis()/1000;
			int nonce = (int) ((Math.random()*9+1)*10000);
			Map<String,String> header = new HashMap<String,String>();
			header.put("App-Key", rongyunappkey);
			header.put("Nonce", nonce+"");
			header.put("Timestamp", timestamp.toString());
			header.put("Signature", DigestUtils.sha1Hex(rongyunappsecret+nonce+timestamp).toString());
			String params = "userId="+rUser.getUserId()+"&name="+rUser.getName()+"&portraitUri="+rUser.getPortraituri();
			try {
				String result = HttpClientUtil.doPost(rongyunurl, params, header);
				JSONObject jObj = JSONObject.parseObject(result);
				TokenEntity tEntity = new TokenEntity();
				tEntity.setUserId(rUser.getUserId());
				tEntity.setToken(jObj.getString("token"));
				tokenDao.insert(tEntity);
				rUser.setRyToken(tEntity.getToken());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return rUser;
	}
	
	/**
	 * 实现获取用户列表
	 */
	@Override
	public List<SysUserResponse> selectList() {
		List<SysUserEntity> uList = this.selectList(null);
		List<SysUserResponse> urList = new ArrayList<SysUserResponse>();
		for (SysUserEntity u : uList) {
			SysUserResponse rUser = new SysUserResponse();
			BeanUtils.copyProperties(u, rUser);
			SysDeptEntity dept = deptDao.selectById(rUser.getDeptId());
			rUser.setDeptName(dept.getName());
			List<SysUserRoleEntity> urs = urDao.selectList(new EntityWrapper<SysUserRoleEntity>().eq("user_id", rUser.getUserId()));
			List<SysRoleResponse> urrs = new ArrayList<SysRoleResponse>();
			for (SysUserRoleEntity ur : urs) {
				SysRoleEntity role = roleDao.selectById(ur.getRoleId());
				SysRoleResponse rr = new SysRoleResponse();
				BeanUtils.copyProperties(role, rr);
				urrs.add(rr);
			}
			rUser.setRoles(urrs);
			
			TokenEntity token = tokenDao.selectById(rUser.getUserId());
			if(null!=token){
				rUser.setRyToken(token.getToken());
			}else{
				Long timestamp=System.currentTimeMillis()/1000;
				int nonce = (int) ((Math.random()*9+1)*10000);
				Map<String,String> header = new HashMap<String,String>();
				header.put("App-Key", rongyunappkey);
				header.put("Nonce", nonce+"");
				header.put("Timestamp", timestamp.toString());
				header.put("Signature", DigestUtils.sha1Hex(rongyunappsecret+nonce+timestamp).toString());
				String params = "userId="+rUser.getUserId()+"&name="+rUser.getName()+"&portraitUri="+rUser.getPortraituri();
				try {
					String result = HttpClientUtil.doPost(rongyunurl, params, header);
					JSONObject jObj = JSONObject.parseObject(result);
					TokenEntity tEntity = new TokenEntity();
					tEntity.setUserId(rUser.getUserId());
					tEntity.setToken(jObj.getString("token"));
					tokenDao.insert(tEntity);
					rUser.setRyToken(tEntity.getToken());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			urList.add(rUser);
		}
		return urList;
	}
}
